package com.woniuxy.controller;

import com.woniuxy.entity.*;
import com.woniuxy.realm.CustomizedToken;
import com.woniuxy.realm.LoginType;
import com.woniuxy.service.CoachService;
import com.woniuxy.service.MessageService;

import com.woniuxy.service.VenueService;
import com.woniuxy.utils.*;
import com.woniuxy.utils.CodeUtils;
import com.woniuxy.utils.LoginRegister;
import com.woniuxy.utils.RegexUtils;
import com.woniuxy.utils.SignInWay;
import com.woniuxy.utils.TimeUtils;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/venue")
public class VenueController {

	@Autowired
	private VenueService venueService;
	@Autowired
	private MessageService messageService;
	@Autowired
	private CoachService coachService;

	private static final String VENUE_LOGIN_TYPE=LoginType.VENUE.toString();

    /**
     * 根据手机号发送验证码
     * @param phoneNumber 手机号
     * @return ResponseEntity
     */
    @PostMapping("/captcha/{phoneNumber}")
    public ResponseEntity<Void> sendCaptcha(@PathVariable("phoneNumber") String phoneNumber, HttpServletRequest request){
        if(!RegexUtils.telphoneIsRight(phoneNumber)){
            return ResponseEntity.ERROR.setMsg("手机号格式错误");
        }
        String captcha = PhoneCode.getCode();
        System.out.println("打印随机验证码："+captcha);
        // 调用发短信的方法
        PhoneCode.sendCode(phoneNumber, captcha);
        HttpSession session=request.getSession();
        session.setAttribute("captcha",captcha);
        return ResponseEntity.SUCCESS.setMsg("发送验证码成功");
    }


    /**
     * 场馆注册方法，在controller进行数据校验
     * @param venue  从前端传来的由MVC封装成的实例
     * @param way   注册方式
     * @return 注册成功返回ResponseEntity.SUCCESS，失败返回ResponseEntity.ERROR
     */
    @PostMapping("/register/{way}")
    public ResponseEntity<Void> venueRegister(@RequestBody Venue venue, @PathVariable("way") int way, HttpServletRequest request){
        HttpSession session=request.getSession();
        //数据校验
        //is null?
        if (venue==null){
            return ResponseEntity.ERROR.setMsg("请正确填写注册信息");
        }
        switch (way){
            //使用用户名注册
            case SignInWay.ACCOUNT :
                //验证用户名是否以字母，数字，英文，中文，下划线，长度2~10
                if (!RegexUtils.accountIsRight(venue.getVname())){
                    return ResponseEntity.ERROR.setMsg("用户名需要是字母、数字、英文、中文、下划线的组合，且长度长度在2~10之间");
                }
                //验证密码长度是否为非空字符并且长度6到12
                if (!RegexUtils.passwordIsRight(venue.getPwd())){
                    return ResponseEntity.ERROR.setMsg("密码需要是非空字符并且长度6到12");
                }
                break;
            //使用手机号注册
            case SignInWay.PHONE :
                //判断手机号格式是否正确
                if (!RegexUtils.telphoneIsRight(venue.getPhoneNumber())){
                    return ResponseEntity.ERROR.setMsg("请输入正确的手机号码");
                }
                String captcha = (String)session.getAttribute("captcha");
                if (!venue.getCaptcha().equals(captcha)){
                    return ResponseEntity.ERROR.setMsg("验证码错误");
                }
                break;
            case SignInWay.QQ :
                //判断QQ号格式是否正确
                if(!RegexUtils.qqIsRight(venue.getQq())){
                    return ResponseEntity.ERROR.setMsg("请输入正确的QQ号码");
                }
                break;

        }
        //校验完成，拿给service查验是否可以
        String pwd = new SimpleHash("MD5", venue.getPwd(), venue.getVname(), 1024).toString();
        venue.setPwd(pwd);
        switch (venueService.addVenue(venue,way)){
            case LoginRegister.REGISTER_SUCCESS:

			if (way == SignInWay.ACCOUNT) {
				Venue venueByVname = venueService.findVenueByVname(venue.getVname());
				session.setAttribute("venue", venueByVname);
			}
			if (way == SignInWay.PHONE) {
				Venue venueByPhoneNumber = venueService.findVenueByPhoneNumber(venue.getPhoneNumber());
				session.setAttribute("venue", venueByPhoneNumber);
			}
			if (way == SignInWay.QQ) {
				Venue venueByQQ = venueService.findVenueByQQ(venue.getQq());
				session.setAttribute("venue", venueByQQ);
			}
			return ResponseEntity.SUCCESS.setMsg("注册成功");
		case LoginRegister.ACCOUNT_EXIST:
			return ResponseEntity.ERROR.setMsg("用户名已存在");
		case LoginRegister.PHONE_EXIST:
			return ResponseEntity.ERROR.setMsg("手机号已经注册过了");
		case LoginRegister.QQ_EXIST:
			return ResponseEntity.ERROR.setMsg("该QQ号已经注册过了");
		}
		return ResponseEntity.ERROR.setMsg("系统维护中。。。。");
	}

	/**
	 * 完善场馆信息完善场馆名
	 *
	 * @param venue
	 *            venue
	 * @return ResponseEntity
	 */
	@PostMapping("/complete")
	public ResponseEntity<Void> completeInfo(@RequestBody Venue venue) {
		// is null?
		if (venue == null) {
			return ResponseEntity.ERROR.setMsg("请正确填写信息");
		}
		// 判断场馆名称是否非空且必须为汉字或英文或组合
		System.out.println("场馆名：" + venue.getNickname());
		if (!RegexUtils.nameIsRight(venue.getNickname())) {
			return ResponseEntity.ERROR.setMsg("场馆名称必须非空且必须为汉字或英文或组合");
		}
		if (venueService.completeInfo(venue) == LoginRegister.OPERATION_SUCCESS) {
			return ResponseEntity.SUCCESS.setMsg("完善信息成功");
		}
		return ResponseEntity.ERROR.setMsg("完善信息失败");
	}

	/**
	 * 注册完之后的图片上传
	 *
	 * @param imageName
	 *            图片名
	 * @param imageFile
	 *            文件数据
	 * @param vid
	 *            场馆id
	 * @return ResponseEntity
	 */
	@PostMapping("/image")
	public ResponseEntity<Void> downloadImages(@RequestParam("name") String imageName,
			@RequestParam("data") MultipartFile imageFile, @RequestParam("vid") int vid,
			@RequestParam("who") String who,HttpServletRequest request) throws IOException {
		ResponseEntity<Void> fileResponseEntity = new ResponseEntity<>();
		System.out.println(imageName);
		System.out.println(imageFile);
		System.out.println(vid);
		if (imageFile.isEmpty()) {
			return fileResponseEntity.setMsg("文件为空").setCode(CodeUtils.ERROR_CODE);
		}
		// 获取文件名
		String fileName = imageFile.getOriginalFilename();
		System.out.println("上传的文件名为:" + fileName);
		if (!RegexUtils.photoIsRight(fileName)) {
			return ResponseEntity.ERROR.setMsg("请上传正确的图片格式");
		}
		// 获取文件的后缀名
		String suffixName = "";
		if (fileName != null && fileName.lastIndexOf(".") != -1) {
			suffixName = fileName.substring(fileName.lastIndexOf("."));
			System.out.println("上传的后缀名为:" + suffixName);
		}

        //获取项目根路径
        String path = request.getServletContext().getRealPath("");
        File root = new File(path);
        File main= root.getParentFile();
		File fileDir = new File(main, "resources/static/images");
        String imageMing = UUID.randomUUID() + suffixName;
//        System.out.println("即将存入硬盘和数据库的图片名：" + imageMing);
		// 检测是否存在目录
        if (!fileDir.exists()) {
            fileDir.mkdirs(); // 创建
        }
        System.out.println("即将存入数据库的图片名："+imageMing);
		Venue venue = new Venue();
		switch (who) {
		case "0":
			venue.setAvatar("../images/"+imageMing);
			break;
		case "1":
			venue.setImage1("../images/"+imageMing);
			break;
		case "2":
			venue.setImage2("../images/"+imageMing);
			break;
		case "3":
			venue.setImage3("../images/"+imageMing);
			break;
		}
		venue.setVid(vid);
        imageMing = fileDir.getAbsolutePath() + File.separator + imageMing;
        System.out.println("即将存入硬盘的图片名："+imageMing);
        File dest = new File(imageMing);
        imageFile.transferTo(dest);
		if (venueService.updateImage(venue) == LoginRegister.OPERATION_SUCCESS) {
			return ResponseEntity.SUCCESS.setMsg("上传场馆成功");
		}
		return ResponseEntity.ERROR.setMsg("上传场馆失败");
	}

    /**
     * 完善场馆地址信息，经纬度等
     * @param venue 封装地址信息
     * @return ResponseEntity
     */
    @PutMapping("/address")
    public ResponseEntity<Void> completeAddress(@RequestBody Venue venue){
        if (venue==null){
            return ResponseEntity.ERROR.setMsg("空数据");
        }
        if (venueService.updateAddressByVenue(venue)==LoginRegister.OPERATION_SUCCESS){
            return ResponseEntity.SUCCESS.setMsg("修改成功");
        }
        return ResponseEntity.ERROR.setMsg("修改失败");
    }

    /**
     * 修改场馆手机号信息
     * @param venue  场馆实例
     * @return ResponseEntity
     */
    @PutMapping("/phoneNumber")
    public ResponseEntity<Void> updatePhoneNumber(@RequestBody Venue venue){
        if (venue==null){
            return ResponseEntity.ERROR.setMsg("空数据");
        }
        if (!RegexUtils.telphoneIsRight(venue.getPhoneNumber())){
            return ResponseEntity.ERROR.setMsg("手机号格式错误");
        }
        if (venueService.updatePhoneNumberByVenue(venue)==LoginRegister.OPERATION_SUCCESS){
            return ResponseEntity.SUCCESS.setMsg("修改成功");
        }
        return ResponseEntity.ERROR.setMsg("修改失败");
    }

    /**
     *场馆登录
     * @param venue 场馆
     * @param way   登录方式
     * @return 注册成功返回ResponseEntity.SUCCESS，失败返回ResponseEntity.ERROR
     */
    @PostMapping("/login/{way}")
    public ResponseEntity<Void> venueLogin(@RequestBody Venue venue,@PathVariable("way") int way, HttpServletRequest request,@RequestParam(value = "rm", defaultValue = "false") boolean rm){
        HttpSession httpSession=request.getSession();
        // 1.获取主题对象，subject 当前用户 对应一个客户端程序
        Subject currentUser = SecurityUtils.getSubject();
        // 获取shiro的session
        Session session = currentUser.getSession();
        //数据校验
        //is null?
        if (venue==null){
            return ResponseEntity.ERROR.setMsg("请正确填写登录信息");
        }
        switch (way){
            //使用用户名登录
            case SignInWay.ACCOUNT :
                //验证用户名是否以字母，数字，英文，中文，下划线，长度2~10
                if (!RegexUtils.accountIsRight(venue.getVname())){
                    return ResponseEntity.ERROR.setMsg("用户名需要是字母、数字、英文、中文、下划线的组合，且长度长度在2~10之间");
                }
                //当前用户没有认证过时
                if (!currentUser.isAuthenticated()) {
                    //验证密码长度是否为非空字符并且长度6到12
                    if (!RegexUtils.passwordIsRight(venue.getPwd())){
                        return ResponseEntity.ERROR.setMsg("密码需要是非空字符并且长度6到12");
                    }
                    // 将账号密码信息封装成token，方便后面认证的操作
                    String pwd = new SimpleHash("MD5", venue.getPwd(), venue.getVname(), 1024).toString();
//                    UsernamePasswordToken token = new UsernamePasswordToken(venue.getVname(), pwd);
                    CustomizedToken customizedToken = new CustomizedToken(venue.getVname(), pwd, VENUE_LOGIN_TYPE);
                    // 判断用户是否勾选
                    if (rm) {
                        //开启记住我的功能
                        customizedToken.setRememberMe(true);
                    }
                    // 当前“用户”拿着令牌去安全管理器中进行身份的认证，会将令牌交给securitymanager进行认证
                    try {
                        currentUser.login(customizedToken);
                        if (venueService.venueLogin(venue,way)!=LoginRegister.LOGIN_SUCCESS){
                            return ResponseEntity.SUCCESS.setMsg("登录失败");
                        }
                        Venue venueByVname = venueService.findVenueByVname(venue.getVname());
                        httpSession.setAttribute("venue", venueByVname);
                        System.out.println("认证成功");
                        return ResponseEntity.SUCCESS.setMsg("登录成功");
                        // 不报任何异常，表示账号不存在
                    } catch (UnknownAccountException e) {
                        // 账号不存在 info为空
                        System.out.println("账号不存在");
                        return ResponseEntity.ERROR.setCode(LoginRegister.ACCOUNT_NOT_EXIST);
                    } catch (IncorrectCredentialsException e) {
                        // 密码错误
                        return ResponseEntity.ERROR.setCode(LoginRegister.PASSWORD_ERROR);
                    } catch (AuthenticationException e) {
                        // 其他异常
                        return ResponseEntity.ERROR.setCode(500);
                    }
                }

                break;
            //使用手机号登录
            case SignInWay.PHONE :
                //判断手机号格式是否正确
                if (!RegexUtils.telphoneIsRight(venue.getPhoneNumber())){
                    return ResponseEntity.ERROR.setMsg("请输入正确的手机号码");
                }
                String captcha = (String)session.getAttribute("captcha");
                System.out.println("获取的验证码："+captcha);
                if (!venue.getCaptcha().equals(captcha)){
                    return ResponseEntity.ERROR.setMsg("验证码错误");
                }
                break;
            case SignInWay.QQ :
                //判断QQ号格式是否正确
                if(!RegexUtils.qqIsRight(venue.getQq())){
                    return ResponseEntity.ERROR.setMsg("请输入正确的QQ号码");
                }
                break;
        }//switch end

		// 校验完成，拿给service查验是否可以
		switch (venueService.venueLogin(venue, way)) {
		case LoginRegister.LOGIN_SUCCESS:
			if (way == SignInWay.ACCOUNT) {
				Venue venueByVname = venueService.findVenueByVname(venue.getVname());
                httpSession.setAttribute("venue", venueByVname);
			}
			if (way == SignInWay.PHONE) {
				Venue venueByPhoneNumber = venueService.findVenueByPhoneNumber(venue.getPhoneNumber());
                httpSession.setAttribute("venue", venueByPhoneNumber);
			}
			if (way == SignInWay.QQ) {
				Venue venueByQQ = venueService.findVenueByQQ(venue.getQq());
                httpSession.setAttribute("venue", venueByQQ);
			}
			return ResponseEntity.SUCCESS.setMsg("登录成功");
		case LoginRegister.ACCOUNT_NOT_EXIST:
			return ResponseEntity.ERROR.setMsg("用户名不存在");
		case LoginRegister.PHONE_NOT_EXIST:
			return ResponseEntity.ERROR.setMsg("该手机号不存在");
		case LoginRegister.QQ_NOT_EXIST:
			return ResponseEntity.ERROR.setMsg("该QQ号未注册过");
		case LoginRegister.PASSWORD_ERROR:
			return ResponseEntity.ERROR.setMsg("密码错误");
		case LoginRegister.CAPTCHA_ERROR:
			return ResponseEntity.ERROR.setMsg("验证码错误");
		case LoginRegister.LOGIN_ERROR:
			return ResponseEntity.ERROR.setMsg("请选择正确的登录方式");
		}
		return ResponseEntity.ERROR.setMsg("系统维护中。。。。");
	}

	/**
	 * 根据场馆id查询场馆
	 *
	 * @param vid
	 *            场馆id
	 * @return 返回ResponseEntity
	 */
	@GetMapping("/find/{vid}")
	public ResponseEntity<Venue> findVenueByVenueId(@PathVariable("vid") int vid) {
		ResponseEntity<Venue> venueResponseEntity = new ResponseEntity<>();
		Venue venueByVenueId = venueService.findVenueByVenueId(vid);
		if (venueByVenueId != null) {
			return venueResponseEntity.setCode(CodeUtils.SUCCESS_CODE).setMsg("给你一个场馆").setData(venueByVenueId);
		}
		return venueResponseEntity.setCode(CodeUtils.ERROR_CODE).setMsg("没有查询到该场馆");
	}

    /**
     * 根据前端传来id和手机号，判断该手机号是不是属于该场馆，且验证码正确
     * 如果通过验证，则返回前端200，表示可以进行密码重置了
     * @param venue 封装了手机号，验证码
     * @return ResponseEntity
     */
    @PostMapping("/check")
    public ResponseEntity<Void> checkPhoneNumber(@RequestBody Venue venue , HttpServletRequest request){
        if (venue==null){
            return ResponseEntity.ERROR.setMsg("请注意，有人在非法传参");
        }
        String phoneNumber = venue.getPhoneNumber();
        HttpSession session = request.getSession();
        Venue venueUseVid = (Venue) session.getAttribute("venue");
        //session中的验证码
        String captcha = (String)session.getAttribute("captcha");
        if (venueUseVid.getVid()!=0&&phoneNumber!=null&&venue.getCaptcha()!=null){
            if (RegexUtils.telphoneIsRight(phoneNumber)) {
                if (venueUseVid.getPhoneNumber().equals(phoneNumber)){
                    if (captcha.equals(venue.getCaptcha())){
                        return ResponseEntity.SUCCESS.setMsg("验证成功");
                    }else { return ResponseEntity.ERROR.setMsg("验证码错误"); }
                }else { return ResponseEntity.ERROR.setMsg("手机号未注册，不是你的手机号");}
            }else {
                return ResponseEntity.ERROR.setMsg("手机号格式错误");
            }
        }
        return ResponseEntity.ERROR.setMsg("参数没给完整");
    }

    /**
     * 将传入的密码进行处理，通过处理则修改数据库中的密码
     * @param venue 取其中的vid和pwd
     * @return ResponseEntity
     */
    @PutMapping("/reset")
    public ResponseEntity<Void> updatePasswordByVenueId(@RequestBody Venue venue){
        if (venue==null){
            return ResponseEntity.ERROR.setMsg("请注意，有人在非法传参");
        }
        if (venue.getVid()!=0&&venue.getPwd()!=null){
            if (RegexUtils.passwordIsRight(venue.getPwd())){
                int i = venueService.updatePasswordByVenueId(venue);
                switch (i){
                    case LoginRegister.OPERATION_SUCCESS :
                        return ResponseEntity.SUCCESS.setMsg("修改密码成功");
                    case LoginRegister.OPERATION_FAILED :
                        return ResponseEntity.ERROR.setMsg("修改密码失败，请重试");
                }
            }else{
                return ResponseEntity.ERROR.setMsg("密码需要是非空字符并且长度6到12");
            }
        }
        return ResponseEntity.ERROR.setMsg("参数没给完整");
    }


    /**
     * 得到所有场馆的分页结果
     * @param venue 场馆条件
     * @return ResponseEntity
     */
    @GetMapping("/all")
    public ResponseEntity<PageBean<Venue>> findAllVenues(@RequestBody Venue venue){
        ResponseEntity<PageBean<Venue>> venueResponseEntity = new ResponseEntity<>();
        if (venue==null){
            return venueResponseEntity.setMsg("非法传参").setCode(CodeUtils.ERROR_CODE);
        }
        List<Venue> venues = venueService.findAllVenues(venue);
        PageBean<Venue> venuePageBean = new PageBean<>();
        venuePageBean.setData(venues);
        return venueResponseEntity.setCode(CodeUtils.SUCCESS_CODE).setMsg("分页结果").setData(venuePageBean);
    }


    /**
     * 得到所有场馆
     * @return ResponseEntity
     */
    @GetMapping("/selectAll")
    public ResponseEntity<List<Venue>> selectAllVenues(){
        ResponseEntity<List<Venue>> venueResponseEntity = new ResponseEntity<>();
        List<Venue> venues = venueService.selectAllVenues();
       if (venues!=null){
           return venueResponseEntity.setCode(CodeUtils.SUCCESS_CODE).setMsg("所有场馆").setData(venues);
       }
        return venueResponseEntity.setCode(CodeUtils.ERROR_CODE).setMsg("出大问题");
    }

    /**
     * 根据用户名找场馆
     * @param vname 用户名
     * @return ResponseEntity<Venue>
     */
    @GetMapping("/vname/{vname}")
    public ResponseEntity<Venue> findVenueByVname(@PathVariable("vname") String vname){
        ResponseEntity<Venue> venueResponseEntity = new ResponseEntity<>();
        Venue venueByVname = venueService.findVenueByVname(vname);
        if (venueByVname!=null){
            return venueResponseEntity.setMsg("来了场馆").setCode(CodeUtils.SUCCESS_CODE).setData(venueByVname);
        }
        return venueResponseEntity.setCode(CodeUtils.ERROR_CODE).setMsg("没找到的嘛");
    }


    /**
     * 根据qq找场馆
     * @param qq qq
     * @return ResponseEntity<Venue>
     */
    @GetMapping("/qq/{qq}")
    public ResponseEntity<Venue> findVenueByQQ(@PathVariable("qq") String qq){
        ResponseEntity<Venue> venueResponseEntity = new ResponseEntity<>();
        Venue venueByQQ = venueService.findVenueByQQ(qq);
        if (venueByQQ!=null){
            return venueResponseEntity.setMsg("来了场馆").setCode(CodeUtils.SUCCESS_CODE).setData(venueByQQ);
        }
        return venueResponseEntity.setCode(CodeUtils.ERROR_CODE).setMsg("没找到的嘛");
    }

    /**
     * 根据phoneNumber找场馆
     * @param phoneNumber phoneNumber
     * @return ResponseEntity<Venue>
     */
    @GetMapping("/phoneNumber/{phoneNumber}")
    public ResponseEntity<Venue> findVenueByPhoneNumber(@PathVariable("phoneNumber") String phoneNumber){
        ResponseEntity<Venue> venueResponseEntity = new ResponseEntity<>();
        Venue venueByPhoneNumber = venueService.findVenueByPhoneNumber(phoneNumber);
        if (venueByPhoneNumber!=null){
            return venueResponseEntity.setMsg("来了场馆").setCode(CodeUtils.SUCCESS_CODE).setData(venueByPhoneNumber);
        }
        return venueResponseEntity.setCode(CodeUtils.ERROR_CODE).setMsg("没找到的嘛");
    }

    /**
     * 获取session中的venue
     * @param request request
     * @return ResponseEntity
     */
    @GetMapping("/session")
    public ResponseEntity<Venue> getVenueInSession(HttpServletRequest request){
        ResponseEntity<Venue> venueResponseEntity = new ResponseEntity<>();
        HttpSession session = request.getSession();
        Venue venue=null;
        if (session!=null){
            System.out.println("session :"+session);
            venue = (Venue)session.getAttribute("venue");
        }else {
            venueResponseEntity.setCode(CodeUtils.ERROR_CODE).setMsg("请先登录");
        }
        if (venue!=null){
            System.out.println("venue:"+venue);
            return venueResponseEntity.setMsg("场馆来了").setCode(CodeUtils.SUCCESS_CODE).setData(venue);
        }
        return venueResponseEntity.setCode(CodeUtils.ERROR_CODE).setMsg("没有场馆");
    }


	// 场馆发送消息
	@RequestMapping("/venuemessage")
	@ResponseBody
	public ResponseEntity venueSendMessage(int id, String messages, HttpServletRequest request) {
		// session中获取当前用户
		HttpSession session = request.getSession();
		Venue venue = (Venue) session.getAttribute("venue");
		// 消息
		// int vid=1;
		Message message = new Message();
		// message.setSender(vid);
		message.setSender(venue.getVid());
		message.setTarget(id);
		String date = TimeUtils.getNowTime();
		message.setSendTime(date);
		message.setContent(messages);
		message.setPurpose("1");
		message.setMstatus("1");
		int num = messageService.sendMessage(message);
		if (num == 1) {
			return ResponseEntity.SUCCESS.setMsg("信息发送成功！");
		}
		return ResponseEntity.ERROR.setMsg("发送失败！");
	}

	// 场馆接受消息
	@RequestMapping("/acceptmessage")
	@ResponseBody
	public ResponseEntity<PageBean<Message>> venueAcceptMessage(String p, HttpServletRequest request) {
		int page = 1;
		if (p != null) {
			page = Integer.parseInt(p);
		}
		HttpSession session = request.getSession();
		Venue venue = (Venue) session.getAttribute("venue");
		ResponseEntity<PageBean<Message>> entity = new ResponseEntity<PageBean<Message>>();
		// 通过账号获取cid
		// int target=1;
		PageBean<Message> message = messageService.getMessageByPage(page, venue.getVid());
		entity.setCode(200);
		entity.setMsg("OK");
		entity.setData(message);
		return entity;

	}

	// 消息查看后，标记为已读
	@RequestMapping("/wasread")
	@ResponseBody
	public ResponseEntity messageWasRead(int mid) {
		int num = messageService.changeMessageStatus(mid);
		if (num == 1) {
			return ResponseEntity.SUCCESS;
		}
		return ResponseEntity.ERROR;
	}

	// 查看场馆签约教练
	@RequestMapping("/mycoach")
	@ResponseBody
	public ResponseEntity<PageBean<Signing>> myCoach(String p, HttpServletRequest request) {
		int page = 1;
		if (p != null) {
			page = Integer.parseInt(p);
		}
		HttpSession session = request.getSession();
		Venue venue = (Venue) session.getAttribute("venue");
		ResponseEntity<PageBean<Signing>> entity = new ResponseEntity<PageBean<Signing>>();

		// 通过账号获取cid
		// int vid = 2;
		// PageBean<Signing> signing = venueService.getCoachByPage(page, vid);
		PageBean<Signing> signing = venueService.getCoachByPage(page, venue.getVid());
		entity.setCode(200);
		entity.setMsg("OK");
		entity.setData(signing);
		return entity;
	}

	// 场馆和教练解约
	@RequestMapping("/cancel")
	@ResponseBody
	public ResponseEntity cancelCoach(int cid, HttpServletRequest request) {
		// session中获取当前场馆账号
		HttpSession session = request.getSession();
		Venue venue = (Venue) session.getAttribute("venue");
		// 解除签约
		// int vid=2;
		// int num=venueService.cancelCoach(vid, cid);
		int num = venueService.cancelCoach(venue.getVid(), cid);
		if (num == 1) {
			return ResponseEntity.SUCCESS.setMsg("已解除签约");
		}
		return ResponseEntity.ERROR.setMsg("解除失败！");
	}

	// 场馆发起签约教练
	@RequestMapping("/sign")
	@ResponseBody
	public ResponseEntity signMessage(int id, HttpServletRequest request) {
		// session中获取当前用户
		HttpSession session = request.getSession();
		Venue venue = (Venue) session.getAttribute("venue");
		// 消息

		Message message = new Message();
		// int vid=1;
		// message.setSender(vid);
		message.setSender(venue.getVid());
		message.setTarget(id);
		String date = TimeUtils.getNowTime();
		message.setSendTime(date);
		message.setContent(venue.getNickname() + "诚邀您加入我们！");
		// message.setContent("第一健身房诚邀您加入我们！");
		// 1表示普通消息2表示签约信息
		message.setPurpose("2");
		// 1表示为确认2表示接受3表示拒绝
		message.setMstatus("1");
		int num = messageService.sendMessage(message);
		if (num == 1) {
			return ResponseEntity.SUCCESS.setMsg("签约信息已发送！");
		}
		return ResponseEntity.ERROR.setMsg("签约信息发送失败！");
	}

	// 场馆对教练发起的签约邀请回应
	@RequestMapping("/venuereply")
	@ResponseBody

	public ResponseEntity<Void> replySign(int reply, int cid, HttpServletRequest request) {

		// 从session中获取用户
		HttpSession session = request.getSession();
		Venue venue = (Venue) session.getAttribute("venue");
		// 接受邀请
		if (reply == 2) {
			// 将该签约信息写入签约表
			Signing signing = new Signing();
			signing.setCid(cid);
			int vid = 1;
			signing.setVid(vid);

			// signing.setCid(coach.getCid());
			signing.setSignTime(TimeUtils.getNowTime());
			// 加入签约表
			int num = venueService.insertCoach(signing);
			// 更改邀约信息状态
			// coachService.changeRmStatus(vid, coach.getCid(), reply);
			coachService.changeRmStatus(cid, vid, reply);
			// 发送接受邀约消息
			Message message = new Message();
			// message.setSender(coach.getCid());
			message.setSender(vid);
			message.setTarget(cid);
			message.setSendTime(TimeUtils.getNowTime());
			// message.setContent(coach.getNickname() + "接受您的邀约！");
			message.setContent("第一俱乐部接受您的邀约！");
			message.setPurpose("2");
			message.setMstatus("1");
			messageService.sendMessage(message);
			if (num == 1) {
				return ResponseEntity.SUCCESS.setMsg("已接受签约！");
			}
		} else if (reply == 3) {
			// 拒绝签约请求
			// coachService.changeRmStatus(vid, coach.getCid(), reply);
			int vid = 1;
			coachService.changeRmStatus(cid, vid, reply);
			// 发送拒绝邀约消息
			Message message = new Message();

			// message.setSender(coach.getCid());
			message.setSender(vid);
			message.setTarget(cid);
			message.setSendTime(TimeUtils.getNowTime());
			// message.setContent(coach.getNickname() + "拒绝您的邀约！");
			message.setContent("教练1拒绝您的邀约！");
			message.setPurpose("2");
			message.setMstatus("1");
			messageService.sendMessage(message);
		}
		return ResponseEntity.ERROR.setMsg("拒绝邀请！");
	}
}
